module.exports = function ($modal, $state, $resource) {

    return {

        restrict: 'E',
        template: require('../views/line_goreturntraffic.html'),
        replace: true,
        scope: {
            'model': '=',
            'util': '=',
        },
        link: function (scope, elements, attrs) {

            //短信模板
            scope.shortMessage = {
                product_id: scope.util.product_id ? scope.util.product_id : '',
                addressTimeArray: [{}]
            };

            scope.date = {
                'label': date2str(new Date()),
                'value': date2str(new Date()),
                'opened': false
            }

            scope.dateOpen = function ($event, item) {
                $event.preventDefault();
                $event.stopPropagation();
                item.opened = true;
            };

            function date2str(d) {
                if (d === undefined) {
                    return "";
                }
                var month = (d.getMonth() + 1).toString();
                var day = d.getDate().toString();
                if (month.length == 1) month = '0' + month;
                if (day.length == 1) day = '0' + day;
                return d.getFullYear() + "-" + month + "-" + day;
            }

            scope.toggleMode = function () {
                $scope.ismeridian = !$scope.ismeridian;
            };

            scope.saveinfoflag = false;

            //交通工具下拉数据模型
            scope.infoarr = [
                { return_mode: '4', name: "--请选择交通工具--" },
                { return_mode: '0', name: "飞机" },
                { return_mode: '1', name: "火车" },
                { return_mode: '2', name: "轮船" },
                { return_mode: '3', name: "汽车" }
            ];
            //交通工具下拉数据模型2(往返交通信息用)
            scope.infoarr_2 = {
                '0': "飞机",
                '1': "火车",
                '2': "轮船",
                '3': "汽车",
                '4': ""
            };

            //飞机舱位下拉数据模型
            scope.houchearr = [
                { return_mode: '', name: "--请选择舱位--" },
                { return_mode: '0', name: "商务座 " },
                { return_mode: '1', name: "一等座" },
                { return_mode: '2', name: "二等座" },
                { return_mode: '3', name: "站票" }
            ];

            //飞机舱位下拉数据模型
            scope.houchearr = [
                { return_mode: '', name: "--请选择舱位--" },
                { return_mode: '0', name: "经济舱" },
                { return_mode: '1', name: "商务舱" },
                { return_mode: '2', name: "头等舱" },
            ];

            //
            scope.example = {
                product_id: scope.util.product_id,
                list: []
            };

            scope.info = {
                // reference_info:'1',
                // departure_mode:'2',
                // return_mode:'1'
            };

            //点击修改按钮
            scope.update = function () {
                scope.saveinfoflag = !scope.saveinfoflag;
            }

            //点击添加参考信息按钮
            scope.addexample = function () {
                if ((scope.info.departure_mode == 4 || scope.info.return_mode == 4) ||
                    (scope.info.departure_mode == '4' || scope.info.return_mode == '4') || scope.saveinfoflag) {
                    alert('请选择并保存往返交通工具');
                    return;
                }
                scope.example.list.push({
                    reference_flight_go: '1',
                    reference_flight_return: '1',
                    go_route: [{
                    }],
                    return_route: [{
                    }]
                });
            }

            //点击删除参考信息按钮
            scope.deljtxx = function (outerIndex) {
                scope.example.list.splice(outerIndex, 1);
            }

            //去程添加上车点
            scope.addgoinfo = function ($index, outerIndex) {
                scope.example.list[outerIndex].go_route.push({
                    departure_time: new Date(),
                    arrival_time: new Date()
                });
            }

            //返程添加上车点
            scope.addreturninfo = function ($index, outerIndex, route) {
                scope.example.list[outerIndex].return_route.push({
                    departure_time: new Date()
                });
            }

            //去程删除上车点
            scope.delgoinfo = function ($index, outerIndex) {
                scope.example.list[outerIndex].go_route.splice($index, 1);
            }

            //返程删除上车点
            scope.delreturninfo = function ($index, outerIndex) {
                scope.example.list[outerIndex].return_route.splice($index, 1);
            }

            //添加集合时间低点
            scope.addAddressTime = function () {
                scope.shortMessage.addressTimeArray.push({});
            }

            //返程集合时间低点
            scope.deleteAddressTime = function ($index) {
                scope.shortMessage.addressTimeArray.splice($index, 1);
            }

            //保存往返交通工具
            scope.save = function () {
                var para = {
                    product_id: scope.util.product_id,
                    departure_mode: scope.info.departure_mode,
                    return_mode: scope.info.return_mode,
                    reference_info: scope.info.reference_info ? 1 : 0
                }
                $resource('/api/ac/lc/productRoundtrafficService/update', {}, {}).save(para, function (res) {
                    if (res.errcode === 0) {
                        scope.saveinfoflag = !scope.saveinfoflag;
                        alert('保存成功');
                        // load();
                    } else {
                        alert(res.errmsg);
                    }
                    if(scope.example.list.length!=1){
                        scope.example.list.push({
                            reference_flight_go: '1',
                            reference_flight_return: '1',
                            go_route: [{
                            }],
                            return_route: [{
                            }]
                        });
                    }
                });
            }

            //保存短信
            scope.savemessAge = function () {
                if(!scope.messageForm.$valid){
                    alert('除备注外其他必填,时间应在合理范围!');
                    return;
                }

                if (!isMobil(scope.shortMessage.tour_guide_mobile)) {
                    alert('请填写正确的电话号码');
                    return;
                }
                if (scope.shortMessage.pick_up_service == 0 || scope.shortMessage.pick_up_service == '0') {
                    scope.shortMessage.remarks = '';
                }
                for (var index = 0; index < scope.shortMessage.addressTimeArray.length; index++) {
                   if (index == 0) {
                       scope.shortMessage.assembling_place = scope.shortMessage.addressTimeArray[index].address + '^' + 
                                                    scope.shortMessage.addressTimeArray[index].time_hour + ':' +
                                                    ((scope.shortMessage.addressTimeArray[index].time_minute.toString().length == 1) ? 
                                                        ('0' + scope.shortMessage.addressTimeArray[index].time_minute.toString()) : 
                                                        (scope.shortMessage.addressTimeArray[index].time_minute.toString()) );
                        continue;
                   }
                   scope.shortMessage.assembling_place += '%' + scope.shortMessage.addressTimeArray[index].address + '^' + 
                                                    scope.shortMessage.addressTimeArray[index].time_hour + ':' +
                                                    ((scope.shortMessage.addressTimeArray[index].time_minute.toString().length == 1) ? 
                                                        ('0' + scope.shortMessage.addressTimeArray[index].time_minute.toString()) : 
                                                        (scope.shortMessage.addressTimeArray[index].time_minute.toString()) );

                    
                }

                //短信
                $resource('/api/ac/lc/messageTemplateService/create', {}, {}).save(scope.shortMessage, function (res) {
                    if (res.errcode === 0) {
                        alert('短信通知 : 保存成功');
                        load();
                    } else {
                        alert('短信通知 :' + res.errmsg);
                    }
                });
            }

            //保存交通信息
            scope.savegoreturn = function () {
                var para = {};
                para = scope.paraSerialize(para, scope.example);


                //交通信息
                $resource('/api/ac/lc/productRoundtrafficService/create', {}, {}).save(para, function (res) {
                    if (res.errcode === 0) {
                        load();
                        alert('交通信息 : 保存成功');
                    } else {
                        alert('交通信息 :' + res.errmsg);
                    }
                });

            };

            //参数序列化
            scope.paraSerialize = function (para, obj) {
                para.product_id = obj.product_id;
                para.list = [];
                var index = 0;
                for (var outindex = 0, paraIndex = 0; outindex < obj.list.length; outindex++) {
                    //去程
                    for (var goindex = 0; goindex < obj.list[outindex].go_route.length; goindex++ , index++) {
                        if (obj.list[outindex].reference_flight_go == 0 || obj.list[outindex].reference_flight_go == '0') {
                            para.list[index] = {};
                            //交通信息
                            para.list[index].traffic_info = parseInt(outindex) + 1;
                            //行程方式
                            para.list[index].mode = '0';
                            //中转
                            para.list[index].transfer = goindex;

                            para.list[index].flt_no = "";
                            para.list[index].aircraft_model = "";
                            para.list[index].airline_company = "";
                            para.list[index].departure_city = obj.list[outindex].departure_city_go || "";
                            para.list[index].arrival_city = obj.list[outindex].arrival_city_go || "";
                            para.list[index].departure_time = "";
                            para.list[index].arrival_time = "";
                            para.list[index].total_time = 0;
                            para.list[index].shipping_space = "";
                            para.list[index].remarks = "";
                            para.list[index].reference_flight = obj.list[outindex].reference_flight_go;
                            para.list[index].train_space = "";
                            // para.list[index].aircraft_model = "";
                            index++;
                            break;
                        }
                        para.list[index] = {};
                        //交通信息
                        para.list[index].traffic_info = parseInt(outindex) + 1;
                        //行程方式
                        para.list[index].mode = '0';
                        //中转
                        para.list[index].transfer = goindex;

                        para.list[index].flt_no = obj.list[outindex].go_route[goindex].flt_no || "";
                        para.list[index].aircraft_model = obj.list[outindex].go_route[goindex].aircraft_model || "";
                        para.list[index].airline_company = obj.list[outindex].go_route[goindex].airline_company || "";
                        para.list[index].departure_city = obj.list[outindex].go_route[goindex].departure_city || "";
                        para.list[index].arrival_city = obj.list[outindex].go_route[goindex].arrival_city || "";
                        para.list[index].departure_time = (obj.list[outindex].go_route[goindex].departure_time_hour &&
                            obj.list[outindex].go_route[goindex].departure_time_minute) ?
                            (obj.list[outindex].go_route[goindex].departure_time_hour + ":" +
                                obj.list[outindex].go_route[goindex].departure_time_minute) : "";
                        para.list[index].arrival_time = (obj.list[outindex].go_route[goindex].arrival_time_hour &&
                            obj.list[outindex].go_route[goindex].arrival_time_minute) ?
                            (obj.list[outindex].go_route[goindex].arrival_time_hour + ":" +
                                obj.list[outindex].go_route[goindex].arrival_time_minute) : "";
                        para.list[index].total_time = parseInt(obj.list[outindex].go_route[goindex].total_time) || 0;
                        para.list[index].shipping_space = obj.list[outindex].go_route[goindex].shipping_space || "";
                        para.list[index].remarks = obj.list[outindex].go_route[goindex].remarks || "";
                        para.list[index].reference_flight = obj.list[outindex].reference_flight_go;
                        para.list[index].train_space = obj.list[outindex].go_route[goindex].train_space || "";
                        // para.list[index].aircraft_model = "";

                    }
                    //返程
                    for (var returnindex = 0; returnindex < obj.list[outindex].return_route.length; returnindex++ , index++) {
                        if (obj.list[outindex].reference_flight_return == 0 || obj.list[outindex].reference_flight_return == '0') {
                            para.list[index] = {};
                            //交通信息
                            para.list[index].traffic_info = parseInt(outindex) + 1;
                            //行程方式
                            para.list[index].mode = '1';
                            //中转
                            para.list[index].transfer = returnindex;

                            para.list[index].departure_city = obj.list[outindex].departure_city_return || "";
                            para.list[index].arrival_city = obj.list[outindex].arrival_city_return || "";
                            para.list[index].departure_time = "";
                            para.list[index].remarks = "";
                            para.list[index].flt_no = "";
                            para.list[index].aircraft_model = "";
                            para.list[index].airline_company = "";
                            para.list[index].arrival_time = "";
                            para.list[index].total_time = 0;
                            para.list[index].shipping_space = "";
                            para.list[index].reference_flight = obj.list[outindex].reference_flight_return || '';
                            para.list[index].train_space = "";
                            // para.list[index].aircraft_model = "";
                            index++;
                            break;
                        }

                        para.list[index] = {};
                        //交通信息
                        para.list[index].traffic_info = parseInt(outindex) + 1;
                        //行程方式
                        para.list[index].mode = '1';
                        //中转
                        para.list[index].transfer = returnindex;

                        para.list[index].departure_city = obj.list[outindex].return_route[returnindex].departure_city || "";
                        para.list[index].departure_time = (obj.list[outindex].return_route[returnindex].departure_time_hour &&
                            obj.list[outindex].return_route[returnindex].departure_time_minute) ?
                            (obj.list[outindex].return_route[returnindex].departure_time_hour + ":" +
                                obj.list[outindex].return_route[returnindex].departure_time_minute) : "";
                        para.list[index].remarks = obj.list[outindex].return_route[returnindex].remarks || "";
                        para.list[index].flt_no = obj.list[outindex].return_route[returnindex].flt_no || "";
                        para.list[index].aircraft_model = obj.list[outindex].return_route[returnindex].aircraft_model || "";
                        para.list[index].airline_company = obj.list[outindex].return_route[returnindex].airline_company || "";
                        para.list[index].arrival_city = obj.list[outindex].return_route[returnindex].arrival_city || "";
                        para.list[index].arrival_time = (obj.list[outindex].return_route[returnindex].arrival_time_hour &&
                            obj.list[outindex].return_route[returnindex].arrival_time_minute) ?
                            (obj.list[outindex].return_route[returnindex].arrival_time_hour + ":" +
                                obj.list[outindex].return_route[returnindex].arrival_time_minute) : "";
                        para.list[index].total_time = parseInt(obj.list[outindex].return_route[returnindex].total_time) || 0;
                        para.list[index].shipping_space = obj.list[outindex].return_route[returnindex].shipping_space || "";
                        para.list[index].reference_flight = obj.list[outindex].reference_flight_return;
                        para.list[index].train_space = obj.list[outindex].return_route[returnindex].train_space || "";
                        // para.list[index].aircraft_model = "";

                    }
                }

                return para;
            }

            var load = function () {

                if (!scope.util.product_id) {
                    return false;
                }

                //交通工具
                $resource('/api/as/lc/roundMessgae/findRoundInfo', {}, {}).save({ product_id: scope.util.product_id ? scope.util.product_id : '' }, function (res) {

                    if (res.errcode === 0) {
                        scope.info.reference_info = res.data.reference_info == 0 ? false : true;
                        scope.info.departure_mode = res.data.departure_mode ? res.data.departure_mode : '4';
                        scope.info.return_mode = res.data.return_mode ? res.data.return_mode : '4';
                    } else {
                        alert('交通工具 :' + res.errmsg);
                    }
                });

                //短信提醒
                $resource('/api/as/lc/roundMessgae/findinfo', {}, {}).save({ product_id: scope.util.product_id ? scope.util.product_id : '' }, function (res) {
                    if (res.errcode === 0 || res.errcode === 10003) {
                        if (angular.isDefined(res.data)) {
                            scope.shortMessage = res.data;
                            scope.shortMessage.addressTimeArray = [];
                            var tempArray = [];
                            tempArray = res.data.assembling_place.split('%');
                            for (var indexAddressTimeArray = 0; indexAddressTimeArray < tempArray.length; indexAddressTimeArray++) {
                                scope.shortMessage.addressTimeArray.push({});
                                scope.shortMessage.addressTimeArray[indexAddressTimeArray].address = tempArray[indexAddressTimeArray].split('^')[0];
                                scope.shortMessage.addressTimeArray[indexAddressTimeArray].time_hour =
                                            parseInt(tempArray[indexAddressTimeArray].split('^')[1].split(':')[0]) ;
                                scope.shortMessage.addressTimeArray[indexAddressTimeArray].time_minute = 
                                            parseInt(tempArray[indexAddressTimeArray].split('^')[1].split(':')[1]) ;
                            }
                            if(scope.shortMessage.addressTimeArray.length < 1){
                                scope.shortMessage.addressTimeArray.push({});
                            }

                            scope.shortMessage.product_id = scope.util.product_id ? scope.util.product_id : '';
                        }
                    } else {
                        alert('短信提醒 :' + res.errmsg);
                    }
                });

                //交通信息
                $resource('/api/ac/lc/productRoundtrafficService/findTrafficList', {}, {}).save({ product_id: scope.util.product_id ? scope.util.product_id : '' }, function (res) {
                    if (res.errcode === 0) {

                        scope.example = {
                            product_id: scope.util.product_id,

                            list: []
                        };

                        //交通信息组数
                        var jiaoTongXinXi = 0;
                        for (var index = 0; index < res.data.list.length; index++) {
                            if (res.data.list[index].traffic_info > jiaoTongXinXi) {
                                jiaoTongXinXi = res.data.list[index].traffic_info
                            }
                        }

                        //交通信息
                        for (var i = 0; i < jiaoTongXinXi; i++) {
                            //创建交通信息
                            scope.addexample();

                            //去程
                            for (var index_go = 0, zhongZhuanIndex = 0; index_go < res.data.list.length; index_go++) {
                                //本组交通 :  去程 : 中转排序
                                if (res.data.list[index_go].traffic_info == (i + 1) && res.data.list[index_go].mode == '0' && res.data.list[index_go].transfer == zhongZhuanIndex) {

                                    scope.example.list[i].departure_city_go = res.data.list[index_go].departure_city;
                                    scope.example.list[i].arrival_city_go = res.data.list[index_go].arrival_city;

                                    scope.example.list[i].reference_flight_go = res.data.list[index_go].reference_flight;
                                    scope.example.list[i].go_route[zhongZhuanIndex] = (res.data.list[index_go]);
                                    scope.example.list[i].go_route[zhongZhuanIndex].departure_time_hour =
                                        res.data.list[index_go].departure_time.split(':')[0];
                                    scope.example.list[i].go_route[zhongZhuanIndex].departure_time_minute =
                                        res.data.list[index_go].departure_time.split(':')[1];
                                    scope.example.list[i].go_route[zhongZhuanIndex].arrival_time_hour =
                                        res.data.list[index_go].arrival_time.split(':')[0];
                                    scope.example.list[i].go_route[zhongZhuanIndex].arrival_time_minute =
                                        res.data.list[index_go].arrival_time.split(':')[1];
                                    zhongZhuanIndex++;
                                }
                            }

                            //返程
                            for (var index_return = 0, zhongZhuanIndex = 0; index_return < res.data.list.length; index_return++) {

                                //本组交通 :  返程 : 中转排序
                                if (res.data.list[index_return].traffic_info == (i + 1) && res.data.list[index_return].mode == '1' && res.data.list[index_return].transfer == zhongZhuanIndex) {

                                    scope.example.list[i].departure_city_return = res.data.list[index_return].departure_city;
                                    scope.example.list[i].arrival_city_return = res.data.list[index_return].arrival_city;

                                    scope.example.list[i].reference_flight_return = res.data.list[index_return].reference_flight
                                    scope.example.list[i].return_route[zhongZhuanIndex] = (res.data.list[index_return]);
                                    scope.example.list[i].return_route[zhongZhuanIndex].departure_time_hour =
                                        res.data.list[index_return].departure_time.substring(0, 2);
                                    scope.example.list[i].return_route[zhongZhuanIndex].departure_time_minute =
                                        res.data.list[index_return].departure_time.substring(3, 5);
                                    scope.example.list[i].return_route[zhongZhuanIndex].arrival_time_hour =
                                        res.data.list[index_return].arrival_time.substring(0, 2);
                                    scope.example.list[i].return_route[zhongZhuanIndex].arrival_time_minute =
                                        res.data.list[index_return].arrival_time.substring(3, 5);
                                    zhongZhuanIndex++;
                                }
                            }
                        }
                    } else {
                        alert('短信提醒 :' + res.errmsg);
                    }
                });
            }
            //初始化用户信息
            load();





            /**
             * 验证手机号
             * @param {需要校验的手机号} mobile
             * @return 错误返回 false , 正确返回 true
             */
            function isMobil(mobile) {
                var patrn = /(^0{0,1}1[3|4|5|6|7|8|9][0-9]{9}$)/;
                if (!patrn.exec(mobile)) {
                    return false;
                }
                return true;
            }

        }

    };

};

